package com.example.musictutor.services.playfunctionobserver;

import java.util.ArrayList;
import java.util.List;

import android.util.Log;

public class PlayFunctions implements PlaySubject {
	public static final int IDLE_STATE = 0;
	public static final int PLAY_PRESSED = 1;
	public static final int PAUSE_PRESSED = 2;
	
	private List<PlayFunctionObserver> observers;
	private int state = 0;
	private boolean changed;
	private final Object MUTEX = new Object();

	public PlayFunctions() {
		this.observers = new ArrayList<PlayFunctionObserver>();
	}
	
	@Override
	public void register(PlayFunctionObserver obj) {
		this.observers.add(obj);
	}

	@Override
	public void unregister(PlayFunctionObserver obj) {
		if(obj == null) 
			throw new NullPointerException("Null Observer");
		
		if(!observers.contains(obj)) 
			observers.add(obj);

	}

	@Override
	public void notifyObservers() {
		Log.d("Observer", "NotifyObservers");
		List<PlayFunctionObserver> observersLocal = null;
		
        // Synchronization basically makes sure that this 
		// method is does not include observers that was registered after the method call
        synchronized (MUTEX) {
            if (!changed)
                return;
            observersLocal = new ArrayList<PlayFunctionObserver>(this.observers);
            this.changed=false;
        }
        
        Log.d("Observer", "Updating observers " + observersLocal.size());
        for (PlayFunctionObserver obj : observersLocal) {
            obj.update();
        }

	}

	@Override
	public int getUpdate(PlayFunctionObserver obj) {
		Log.d("Observer", "getUpdate");
		return state;
	}

	
	public void postMessage(int state) {
		this.state = state;
		this.changed = true;
		notifyObservers();
	}
}
